package org.fastsyncer.plugin.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.constant.ThirdpartyConstant;
import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.common.util.AESEncyptUtil;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.plugin.AbstractConvert;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <ul>
 *  <dt>星盾企业组织同步到应用组织转换规则：</dt>
 *  <dl>
 *      <li>通过HTTP协议请求星盾</li>
 *      <li>createOrgUnit(...)</li>
 *      <li>updateOrgUnit(...)</li>
 *      <li>deleteOrgUnit(...)</li>
 *  </dl>
 * </ul>
 * 
 * @author AE86
 * @date 2018年04月12日 上午9:32:12
 * @version 1.0.0
 */
public class AostarBaseOrgToAppOrgConvertImpl extends AbstractConvert {

    private final Logger logger = LoggerFactory.getLogger(AostarBaseOrgToAppOrgConvertImpl.class);

    /**
     * http://10.238.206.223:18200/asdview/coremail/rest/coremail
     */
    private final String URL = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_AOSTAR_APPORG_REQUEST_URL);

    /**
     * /createOrgUnit
     */
    private final String OPR_INSERT = "/createOrgUnit";

    /**
     * /updateOrgUnit
     */
    private final String OPR_UPDATE = "/updateOrgUnit";

    /**
     * /deleteOrgUnit
     */
    private final String OPR_DELETE = "/deleteOrgUnit";

    @Override
    public String getConvertName() {
        return "企业组织_应用组织转换";
    }

    @Override
    public void convert(MappingTask task, List<Map<String, Object>> source, List<Map<String, Object>> target) {

    }

    @Override
    public void convert(MappingTask task, Map<String, Object> source, Map<String, Object> target, String event, Map<String, Object> beforeData) {
        if (null == target || target.isEmpty()) {
            return;
        }
        // 转换参数
        List<NameValuePair> list = this.toList(target);
        if (null == list || list.isEmpty()) {
            return;
        }

        // 判断逻辑删除
        Object isDel = target.get("IS_DELETED");
        String isDelStr = null == isDel ? "" : String.valueOf(isDel);
        if ("1".equals(isDelStr)) {
            this.post(URL + OPR_DELETE, list);
        } else {
            // 按照事件发送请求
            switch (event) {
            case ConnectorConstant.OPERTION_INSERT:
                this.post(URL + OPR_INSERT, list);
                break;
            case ConnectorConstant.OPERTION_UPDATE:
                this.post(URL + OPR_UPDATE, list);
                break;
            case ConnectorConstant.OPERTION_DELETE:
                this.post(URL + OPR_DELETE, list);
                break;
            default:
                break;
            }
        }
    }

    private List<NameValuePair> toList(Map<String, Object> target) {
        Map<String, Object> row = new HashMap<String, Object>();
        row.put("id", target.get("ID"));
        row.put("parentId", target.get("PARENT_ID"));
        row.put("orgPath", target.get("ORG_PATH"));
        row.put("orgName", target.get("ORG_NAME"));
        row.put("appId", target.get("APP_ID"));
        JSONObject obj = new JSONObject(row);
        try {
            String json = AESEncyptUtil.encrypt(obj.toString(), AESEncyptUtil.keySeed);
            List<NameValuePair> list = new ArrayList<NameValuePair>(1);
            list.add(new BasicNameValuePair("json", json));
            return list;
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
        }
        return null;
    }

    /**
     * 发送HTTP POST请求
     * @param url
     * @param args
     */
    private void post(String url, List<NameValuePair> args) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // URL
            HttpPost post = new HttpPost(url);
            if(logger.isDebugEnabled()){
                logger.debug(url);
                logger.debug(args.toString());
            }
            UrlEncodedFormEntity arg = new UrlEncodedFormEntity(args, "UTF-8");
            post.setEntity(arg);
            // 发送请求
            response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String msg = EntityUtils.toString(entity);
            logger.info(msg);
        } catch (ClientProtocolException e) {
            logger.error(e.getLocalizedMessage());
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != client) {
                    client.close();
                }
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage());
            }
        }

    }

}
